//
//  TNAccountTableViewController.m
//  TravelNotes
//
//  Created by 黄锋 on 15/8/13.
//  Copyright (c) 2015年 王浩宇. All rights reserved.
//

#import "TNAccountTableViewController.h"
#import "FMDB.h"
#import "TNAccountModel.h"
#import "TNAccountTableViewCell.h"
#import "TNAddAccountTableViewController.h"
#import "Macro.h"
#import "TNCostAmountTableViewController.h"

#define kDestinationsInfos @"destinationsInfos"

@interface TNAccountTableViewController ()

@property(nonatomic, strong) FMDatabase *db;
@property(nonatomic, strong) NSMutableArray *dataArr;//数据库获取全部信息
@property(nonatomic, strong) NSArray *titleArr;//分区标题
@property(nonatomic, strong) NSArray *moneyArray;//币种
@property(nonatomic, strong) NSMutableArray *accountArr;//消费总账
@property(nonatomic, strong) NSString *str;//数据库表名

@property(nonatomic, strong) TNAddAccountTableViewController *addVC;

@end

@implementation TNAccountTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleArr = @[@"消费总账", @"消费明细", @""];
    if (_currency_display) {
        self.moneyArray = @[_currency_display, @"人民币", @"美元", @"欧元"];
    } else {
        self.moneyArray = @[@"元", @"人民币", @"美元", @"欧元"];
    }
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH - 40, 10, 40, 40);
    [button setImage:[UIImage imageNamed:@"AddBarButton"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addAccount) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.title = @"旅行记账";
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[TNAccountTableViewCell class] forCellReuseIdentifier:@"TNAccountTableViewCell"];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"FMDB.db"];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
//        NSLog(@"数据库打开失败");
    } else {
        NSNumber *num = [[NSUserDefaults standardUserDefaults] objectForKey:kDestinationsInfos];
        _str = [NSString stringWithFormat:@"Account%@",  num];
//        NSLog(@"TABLE:%@", _str);
         if (![self isExistTable:_str]) {
             NSString *sql = [NSString stringWithFormat:@"CREATE TABLE %@ (money text, unit text, consume text, detailed text, time text)", _str];
            [_db executeUpdate:sql];
         } else {
             [self getDataArr];
         }
    }
}

- (BOOL) isExistTable:(NSString *)tableName
{
    FMResultSet *rs = [_db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    return NO;
}

- (void)getDataArr
{
    if (_dataArr) {
        [_dataArr removeAllObjects];
    } else {
        _dataArr = [NSMutableArray array];
    }
    NSMutableArray *array = [@[@"0", @"0", @"0", @"0"] mutableCopy];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM '%@'", _str];
    FMResultSet *rs = [_db executeQuery:sql];
    while ([rs next]) {
        NSString *money = [rs stringForColumn:@"money"];
        NSString *unit = [rs stringForColumn:@"unit"];
        NSString *consume = [rs stringForColumn:@"consume"];
        NSString *detailed = [rs stringForColumn:@"detailed"];
        NSString *time = [rs stringForColumn:@"time"];
        for (int i = 0; i < 4; i++) {
            NSString *str = _moneyArray[i];
            if ([str isEqualToString:unit]) {
                CGFloat total = [array[i] floatValue] + [money floatValue];
                [array replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%.2f", total]];
                break;
            }
        }
        TNAccountModel *model = [[TNAccountModel alloc] initWithMoney:money unit:unit consume:consume detailed:detailed time:time];
        [_dataArr addObject:model];
    }
    [rs close];
    self.accountArr = array;
    [self.tableView reloadData];
}

- (void)addAccount
{
    _addVC = [[TNAddAccountTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    _addVC.model = nil;
    _addVC.db = _db;
    _addVC.str = _str;
    _addVC.isNew = YES;
    _addVC.unitArr = _moneyArray;
    __weak typeof(self)  weakSelf = self;
    _addVC.myBlock = ^{
        [weakSelf getDataArr];
    };
    [self.navigationController pushViewController:_addVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableViewDataSourse

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_dataArr.count) {
        return 3;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger num = 0;
    if (!_dataArr.count) {
        return 1;
    }
    switch (section) {
        case 0:
            num = 2;
            break;
        case 1:
            num = _dataArr.count;
            break;
        case 2:
            num = 1;
            break;
        default:
            break;
    }
    return num;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 80;
    } else {
        return 40;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return _titleArr[section];
}

- (NSString *)totalAccountString
{
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i < 4; i++) {
        if ([_accountArr[i] floatValue] > 0) {
            [str appendString:[NSString stringWithFormat:@",%@%@", _accountArr[i], _moneyArray[i]]];
        }
    }
    if (str.length) {
        [str replaceCharactersInRange:NSMakeRange(0, 1) withString:@"共"];
    }
    return str;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArr.count) {
        switch (indexPath.section) {
            case 0:
            {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
                if (indexPath.row == 0) {
                    cell.textLabel.text = [self totalAccountString];
                    cell.accessoryType = UITableViewCellAccessoryNone;
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                } else {
                    cell.textLabel.text = @"查看消费统计";
                    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
                return cell;
            }
            case 1:
            {
                TNAccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TNAccountTableViewCell" forIndexPath:indexPath];
                cell.model = _dataArr[indexPath.row];
                return cell;
            }
            case 2:
            {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
                cell.textLabel.text = @"清除消费记录";
                cell.textLabel.textAlignment = NSTextAlignmentCenter;
                cell.textLabel.textColor = [UIColor redColor];
                return cell;
            }
            default:
                break;
        }
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.textLabel.text = @"暂无消费记录";
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        _addVC = [[TNAddAccountTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        _addVC.model = _dataArr[indexPath.row];
        _addVC.db = _db;
        _addVC.str = _str;
        _addVC.isNew = NO;
        _addVC.unitArr = _moneyArray;
        __weak typeof(self) weakSelf = self;
        _addVC.myBlock = ^{
            [weakSelf getDataArr];
        };
        [self.navigationController pushViewController:_addVC animated:YES];
    } else if (indexPath.section == 2) {
            NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@", _str];
            [_db executeUpdate:sql];
            [self getDataArr];
    } else if (indexPath.section == 0 && indexPath.row == 1) {
        TNCostAmountTableViewController *costAmountVC = [[TNCostAmountTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        costAmountVC.dataArr = _dataArr;
        [self.navigationController pushViewController:costAmountVC animated:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
